package util;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ResourceBundle;

public final class JDBCUtil {
    //定义数据库连接相关参数
    static Connection connection = null;
    //私有化构造方法
    private JDBCUtil(){}

    //加载配置文件
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");//加载驱动程序
            connection = DriverManager.getConnection
                    ("jdbc:mysql://localhost:3306/bookstore?serverTimezone=CST&characterEncoding=utf8","root","123456");
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取数据库连接
    public static Connection getConnection() {
        return connection;
    }
    //关闭资源
    public static void closeAll(Connection con, Statement stmt, ResultSet rs){
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static <T> T parseResultSet(ResultSet rs,Class<T> cls) {
        try {
            //只会将查询的第一天数据转换为对象
            if(rs.next()){
                //实例化对象
                T obj = cls.newInstance();
                //获取类中所有的属性
                Field[] arrf = cls.getDeclaredFields();
                //遍历属性
                for(Field f : arrf){
                    //设置忽略访问校验
                    f.setAccessible(true);
                    //为属性设置内容
                    f.set(obj, rs.getObject(f.getName()));
                }
                return obj;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
